/*
 *  tf_listmodel.cpp
 *  Perceel
 *
 *  Created by Nicola Gigante on 17/03/08.
 *  Copyright 2008 Nicola Gigante. All rights reserved.
 *
 */

#include "tf_listmanager.h"

QVariant TFListManager::data(const QModelIndex &index, int/* role */) const
{
	QVariant v = QVariant::fromValue(functions[index.row()]);
	
	return v;
}

void TFListManager::addFunction(TF tf)
{
	beginInsertRows(QModelIndex(), functions.count() + 1, functions.count() + 1);
	functions.append(tf);
	endInsertRows();
	setModified(true);
}

void TFListManager::delFunction(int f)
{
	beginRemoveRows(QModelIndex(), f, f);
	functions.removeAt(f);
	endRemoveRows();
	setModified(true);
}

bool TFListManager::open(QString name)
{
	QFile f(name);
	if(!f.open(QIODevice::ReadOnly | QIODevice::Text))
		return false;
	
	setFilename(name);
	TFReader r(&f);
	QList<TF> l;
	try
	{
		l = r.read();
	}catch(...)
	{
		return false;
	}
	
	beginInsertRows(QModelIndex(), 0, l.count());
	functions = l;
	endInsertRows();
	setModified(false);
	
	return true;
}

bool TFListManager::save()
{
	if(m_modified)
	{
		QFile f(filename());
		if(!f.open(QIODevice::WriteOnly | QIODevice::Text))
			return false;
	
		TFWriter w(&f);
		w.write(functions);	
	
		f.close();
		setModified(false);
	}
	
	return true;
}
